/*
* 分页组件，服务端渲染分页
* 
*/
import { useState, useEffect } from 'react'
import { useRouter } from 'next/router'
import { Pagination } from 'antd'
import { pagination } from "@/config"

export default function MyPagination({ root, total }) {

    const router = useRouter(),
          { query, asPath } = router;

    let currPage = 1;

    if(asPath.includes('/list_')){
        currPage = parseInt(asPath.split('_')[1]) || 2;
        currPage = Number(currPage);
    }
    
    const [curr, setCurr] = useState(currPage);

    // 当前页面
    useEffect(() => {
        setCurr(currPage)
    }, [currPage])

    if (!total) {
        return <></>
    }

    // 翻页
    const pageHandler = (curr) => {
        let newPath = root,
            newQuery = { ...query };
        if(curr > 1){
            newPath += `/list_${curr}`;
        }
        setCurr(curr);
        router.push({
            pathname: newPath,
            query: newQuery
        });
    }

    return (
        <div className="list-pagination">
            <Pagination
                total={total}
                showTotal={total => `共${total}条数据`}
                pageSize={pagination.pageSize}
                current={curr}
                onChange={(curr) => {
                    pageHandler(curr)
                }}
            />
        </div>
    )
}